using UnityEngine;
using System.Net;
using System.Collections;
using System.Collections.Generic;

public class GameMenus : MonoBehaviour
{
    public string playerName;
    public GameManager gameManager;
    public Networking networkManager;
    //chat fields
    public Chat chatBox;

    public delegate void GUIMenu();
    public GUIMenu currentMenu;

    private float lastHostListRequest = -1000f;
    private float hostListRefreshTimeout = 10f;

    //Game list field
    public float tableWidth = 476;
    public float tableHeight = 200;
    public float gameNameWidth = 150;
    public float nbPlayersWidth = 60;
    public float commentWidth = 150;
    public float joinButtonWidth = 70;
    public float lineHeigth = 20;
    public float cellSpace = 5;
    public float lineSpace = 2;
    public Vector2 scrollGames;

    //Windows fields
    private bool showHostWindow = false;
    private bool showIpWindow = false;
    private Rect windowPopUp;

    private string gameName = "New Game";
    private string serverIp = "127.0.0.1";
    private string serverPort = "25001";
    private string nbPlayers = "8";
    private string maxKills = "15";
	
	public Texture2D warTexture;
	public Texture2D wizTexture;
	public Texture2D rogTexture;

    public void Awake()
    {
        if (playerName == "")
        {
            playerName = PlayerPrefs.GetString("playerName");
        }
        currentMenu = HostJoin;
    }

    public void DrawGUI()
    {
        //TODO : Replace by a background image
        GUILayout.Label("Project DarkArena");
        currentMenu();
    }
    public void HostJoin()
    {
		//Quit
		//
		GUILayout.BeginArea(new Rect(Screen.width / 2 - 175, Screen.height / 2 - 100, 350, 200));

        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        GUILayout.Label("Enter your name :");
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        playerName = GUILayout.TextField(playerName, GUILayout.MaxWidth(120), GUILayout.MinWidth(120));
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("Quit", GUILayout.MaxWidth(60)))
        {
            Application.Quit();
        }
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
		//
		//
        windowPopUp = new Rect(Screen.width / 2 - 125, Screen.height / 2 - 175, 250, 350);

        if (showIpWindow)
        {
            windowPopUp = GUI.Window(0, windowPopUp, JoinByIP, "Join a Game by IP");
        }

        if (showHostWindow)
        {
            windowPopUp = GUI.Window(0, windowPopUp, HostGame, "Host a Game");
        }
		
		//Game List
        float xTopLeft = (Screen.width - tableWidth) / 2;
        GUILayout.BeginArea(new Rect(xTopLeft, ((Screen.height - tableHeight) / 3 + tableHeight + 45), tableWidth, 30));
        GUILayout.BeginHorizontal();

        GUI.enabled = !(showHostWindow || showIpWindow);

        if (GUILayout.Button("Enter an IP"))
        {
            showIpWindow = true; //display the popup window
			gameManager.playerName = playerName;
        }
        if (GUILayout.Button("Host a Game"))
        {
            showHostWindow = true; //display the popup window
			gameManager.playerName = playerName;
        }

        GUILayout.EndHorizontal();
        GUILayout.EndArea();
    }
	
	public void InitializeChat(){
		 PlayerPrefs.SetString("playerName", playerName);
            gameManager.playerName = playerName;
            chatBox.pseudo = playerName;
            //currentMenu = GamesListMenu;
	}
    /// <summary>
    /// Open a GUI Window to connect by server ip
    /// </summary>
    public void JoinByIP(int windowID)
    {
        GUILayout.Label("Server IP :");
        serverIp = GUILayout.TextField(serverIp, GUILayout.MinWidth(100));
        GUILayout.Label("Server port :");
        serverPort = GUILayout.TextField(serverPort);

        if (GUILayout.Button("Connect"))
        {
            int port = int.Parse(serverPort);
            showIpWindow = false;
            networkManager.DirectConnectToServer(serverIp, port);
			InitializeChat();
        }
        if (GUILayout.Button("Back"))
        {
            showIpWindow = false;
        }
    }

    /// <summary>
    /// Open a GUI Windows to configure a host game
    /// </summary>
    public void HostGame(int windowID)
    {
        //networkManager.TestConnection(); //update test
        //Debug.Log("Test result : " + gameManager.testMessage);
        //Debug.Log(gameManager.shouldEnableNatMessage);

        GUILayout.Label("Game Name :");
        gameName = GUILayout.TextField(gameName, GUILayout.MinWidth(50));
        GUILayout.Label("Server port :");
        serverPort = GUILayout.TextField(serverPort);
		
		
		if (GUILayout.Button("Start"))
        {
            //initialise server/game manager
            int port = int.Parse(serverPort);
            showHostWindow = false;
            networkManager.StartServer(gameName, port);
			InitializeChat();
        }
        //let start a server only when the NAT test is done
        //GUI.enabled = networkManager.doneTesting;
        /*if (networkManager.doneTesting)
        {
            if (GUILayout.Button("Start"))
            {
                //initialise server/game manager
                int port = int.Parse(serverPort);
                showHostWindow = false;
                networkManager.StartServer(gameName, port);
				InitializeChat();
            }
        }
        else
        {
            GUILayout.Button(networkManager.testStatus);
        }*/
        GUI.enabled = true;

        if (GUILayout.Button("Back"))
        {
            showHostWindow = false;
        }
    }

    /// <summary>
    /// This is the looby
    /// </summary>
    public void ChatRoom()
    {
		Rect rect = new Rect(10, (Screen.height * 0.45f), 300, (Screen.height * 0.5f));
        chatBox.DrawChat(rect);
        //Connected Players List
        GUI.Box(new Rect((Screen.width * 0.75f) + 25, 50, (Screen.width * 0.25f) - 50, Screen.height * 0.5f), "Players");
        GUILayout.BeginArea(new Rect((Screen.width * 0.75f) + 25, 50, (Screen.width * 0.25f) - 25, (Screen.height * 0.5f) - 50));
        GUILayout.Space(15);
        GUILayout.BeginVertical();
        foreach (KeyValuePair<string, NetworkPlayer> player in networkManager.playersByName)
        {
			GUILayout.BeginHorizontal();
			Color color = new Color();
			if ( networkManager.readyPlayers.ContainsKey(player.Value))
			{
				if ( networkManager.readyPlayers[player.Value] )
				{
					color = Color.cyan;
				}
				else
				{
					color = Color.white;
				}
				GUI.color = color;
	            GUILayout.Label(player.Key);
				if ( networkManager.readyPlayers.ContainsKey(Network.player) && player.Value == Network.player )
				{
					if ( ! networkManager.readyPlayers[Network.player] && networkManager.readyPlayers.Count == 2 )
					{
						if (GUILayout.Button("Ready", GUILayout.MaxWidth(60)))
				        {
							networkManager.NewPlayerReady();
				        }
					}
				}
						GUI.color = Color.white;
					}
			GUILayout.EndHorizontal();
		  }
        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
	
	public void SelectClass()
    {
		Rect rect = new Rect(0, (Screen.height * 0.7f), (Screen.width * 0.7f), (Screen.height * 0.3f));
        chatBox.DrawChat(rect);
    }

    public void OnServerInitialized()
    {
        chatBox.SetWindowChat(25, 50, (Screen.width * 0.75f) - 25, (Screen.height * 0.5f) - 41);
        currentMenu = ChatRoom;
    }

    public void OnConnectedToServer()
    {
        chatBox.SetWindowChat(25, 50, (Screen.width * 0.75f) - 25, (Screen.height * 0.5f) - 41);
        currentMenu = ChatRoom;
    }
	
	public void OnPlayersReady()
    {
        currentMenu = SelectClass;
    }

    public void OnDisconnectedFromServer(NetworkDisconnection info)
    {
        currentMenu = HostJoin;
    }

    public void OnFailedToConnect(NetworkConnectionError error)
    {
        currentMenu = HostJoin;
    }

    public void OnFailedToConnectToMasterServer(NetworkConnectionError error)
    {
        currentMenu = HostJoin;
    }
	public void InfoNeutralChat(string msg)
	{
		if ( Network.isServer && !gameManager.isDebugFightingScene) // seulement l'host qui envoi les infos
		{
			chatBox.AddAnnonce(msg, "", "yellow");	
		}
	}
}
